﻿/*
 * 序列化 和 反序列化
 * C# 对象 => Json对象
 * Json对象 => C#对象
 */


// JSON

using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;


var userInfo = new User() { Name = "李四", Age = 22, Roles = new[] { "管理员", "运维" } };
var json = JsonSerializer.Serialize(userInfo, new JsonSerializerOptions()
{
    Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
});

/********************************************************************************************/

string jsonStr = """
    {
    "Name":"张三",
    "Age":18,
    "Roles":["开发者","运维"]
    }
    """;

var data = JsonSerializer.Deserialize<User>(jsonStr);

/********************************************************************************************/

using var reader = new StreamReader("jsonDome.json");
string jsonDomeFileContent = reader.ReadToEnd();
var userInfos = JsonSerializer.Deserialize<List<User>>(jsonDomeFileContent);

userInfos.ForEach(x => Console.WriteLine(x.ToString()));

/********************************************************************************************/
using var readerNew = new StreamReader("jsonDomeNew.json");
string jsonDomeNewFileContent = readerNew.ReadToEnd();
var users = JsonSerializer.Deserialize<Dictionary<string, User>>(jsonDomeNewFileContent);
foreach (var keyValuePair in users)
{
    Console.WriteLine($"ID:{keyValuePair.Key}");
    Console.WriteLine($"{keyValuePair.Value.ToString()}");
}

class User
{
    public string Name { get; set; }

    public int Age { get; set; }

    public string[] Roles { get; set; }

    public override string ToString()
    {
        return $"Name:{Name}\r\nAge:{Age}\r\nRoles:{string.Join(",", Roles)}";
    }
}